#!/bin/bash

# 腾讯云COS签名调试脚本

set -e

# 配置测试参数
TENCENT_SECRET_ID=""
TENCENT_SECRET_KEY=""
TENCENT_BUCKET="claude-code-mirror-1251234567"
TENCENT_REGION="ap-beijing"

# 加载环境变量
if [ -f ".env" ]; then
    echo "加载 .env 文件..."
    source .env
fi

# 检查配置
check_config() {
    echo "检查配置..."
    echo "TENCENT_SECRET_ID: ${TENCENT_SECRET_ID:0:8}..."
    echo "TENCENT_SECRET_KEY: ${TENCENT_SECRET_KEY:0:8}..."
    echo "TENCENT_BUCKET: $TENCENT_BUCKET"
    echo "TENCENT_REGION: $TENCENT_REGION"

    if [ -z "$TENCENT_SECRET_ID" ] || [ -z "$TENCENT_SECRET_KEY" ] || [ -z "$TENCENT_BUCKET" ] || [ -z "$TENCENT_REGION" ]; then
        echo "❌ 配置不完整"
        exit 1
    fi

    echo "✅ 配置检查通过"
}

# 测试简单的GET请求
test_get_request() {
    echo ""
    echo "测试GET请求..."

    local method="GET"
    local host="${TENCENT_BUCKET}.cos.${TENCENT_REGION}.myqcloud.com"
    local uri="/"
    local start_time=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    local end_time=$(date -u -d "+1 day" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u -v+1d +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null)
    local key_time="$start_time;$end_time"
    local sign_time="$start_time;$end_time"

    local header_list="host"
    local header_list_lowercase="host"
    local url_param_list=""
    local url_param_list_lowercase=""

    local http_string="$method\n$uri\n\nhost:$host\n\n\n"
    local http_string_sha256=$(echo -n "$http_string" | openssl dgst -sha256 | cut -d' ' -f2)

    local string_to_sign="sha256\n$sign_time\n$header_list_lowercase\n$url_param_list_lowercase\n$http_string_sha256"

    local secret_key=$(echo -n "$key_time" | openssl dgst -sha256 -hmac "$TENCENT_SECRET_KEY" -binary | xxd -p | tr '[:lower:]' '[:upper:]')
    local signature_key=$(echo -n "$secret_key" | openssl dgst -sha256 -hmac "$TENCENT_SECRET_KEY" -binary | xxd -p | tr '[:lower:]' '[:upper:]')
    local signature=$(echo -n "$string_to_sign" | openssl dgst -sha256 -mac HMAC -macopt hexkey:"$signature_key" -binary | base64)

    local authorization="q-sign-algorithm=sha1&q-ak=$TENCENT_SECRET_ID&q-sign-time=$sign_time&q-key-time=$key_time&q-header-list=$header_list_lowercase&q-url-param-list=$url_param_list_lowercase&q-signature=$signature"

    echo "请求详情:"
    echo "  URL: https://$host$uri"
    echo "  Authorization: $authorization"
    echo "  HTTP String: $http_string_sha256"
    echo "  String to Sign: $string_to_sign"

    echo ""
    echo "发送GET请求..."

    if response=$(curl -s -w "\nHTTP_CODE:%{http_code}" \
        -H "Host: $host" \
        -H "Authorization: $authorization" \
        "https://$host$uri"); then

        http_code=$(echo "$response" | grep "HTTP_CODE:" | cut -d: -f2)
        body=$(echo "$response" | sed 's/HTTP_CODE:.*$//')

        echo "HTTP状态码: $http_code"
        echo "响应内容: $body"

        if [ "$http_code" = "200" ]; then
            echo "✅ GET请求成功"
        else
            echo "❌ GET请求失败"
        fi
    else
        echo "❌ 请求发送失败"
    fi
}

# 测试PUT请求（上传小文件）
test_put_request() {
    echo ""
    echo "测试PUT请求..."

    # 创建测试文件
    local test_file="/tmp/test_upload.txt"
    echo "Hello Tencent COS! $(date)" > "$test_file"

    local method="PUT"
    local host="${TENCENT_BUCKET}.cos.${TENCENT_REGION}.myqcloud.com"
    local uri="/test-file.txt"
    local content_type="text/plain"
    local start_time=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    local end_time=$(date -u -d "+1 day" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u -v+1d +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null)
    local key_time="$start_time;$end_time"
    local sign_time="$start_time;$end_time"

    local header_list="content-type;host"
    local header_list_lowercase=$(echo "$header_list" | tr '[:upper:]' '[:lower:]')
    local url_param_list=""
    local url_param_list_lowercase=""

    local http_string="$method\n$uri\n\ncontent-type:$content_type\nhost:$host\n\n\n"
    local http_string_sha256=$(echo -n "$http_string" | openssl dgst -sha256 | cut -d' ' -f2)

    local string_to_sign="sha256\n$sign_time\n$header_list_lowercase\n$url_param_list_lowercase\n$http_string_sha256"

    local secret_key=$(echo -n "$key_time" | openssl dgst -sha256 -hmac "$TENCENT_SECRET_KEY" -binary | xxd -p | tr '[:lower:]' '[:upper:]')
    local signature_key=$(echo -n "$secret_key" | openssl dgst -sha256 -hmac "$TENCENT_SECRET_KEY" -binary | xxd -p | tr '[:lower:]' '[:upper:]')
    local signature=$(echo -n "$string_to_sign" | openssl dgst -sha256 -mac HMAC -macopt hexkey:"$signature_key" -binary | base64)

    local authorization="q-sign-algorithm=sha1&q-ak=$TENCENT_SECRET_ID&q-sign-time=$sign_time&q-key-time=$key_time&q-header-list=$header_list_lowercase&q-url-param-list=$url_param_list_lowercase&q-signature=$signature"

    echo "PUT请求详情:"
    echo "  URL: https://$host$uri"
    echo "  Content-Type: $content_type"
    echo "  File: $test_file"
    echo "  HTTP String SHA256: $http_string_sha256"
    echo "  String to Sign: $string_to_sign"

    echo ""
    echo "发送PUT请求..."

    if response=$(curl -s -w "\nHTTP_CODE:%{http_code}" \
        -X PUT \
        -H "Content-Type: $content_type" \
        -H "Host: $host" \
        -H "Authorization: $authorization" \
        -H "x-cos-content-sha256: $http_string_sha256" \
        --upload-file "$test_file" \
        "https://$host$uri"); then

        http_code=$(echo "$response" | grep "HTTP_CODE:" | cut -d: -f2)
        body=$(echo "$response" | sed 's/HTTP_CODE:.*$//')

        echo "HTTP状态码: $http_code"
        echo "响应内容: $body"

        if [ "$http_code" = "200" ]; then
            echo "✅ PUT请求成功"
        else
            echo "❌ PUT请求失败"
        fi
    else
        echo "❌ 请求发送失败"
    fi

    # 清理测试文件
    rm -f "$test_file"
}

# 主函数
main() {
    echo "======================================"
    echo "  腾讯云COS签名调试"
    echo "======================================"

    check_config
    test_get_request
    test_put_request

    echo ""
    echo "调试完成！"
}

# 运行主函数
main "$@"